import axios from 'axios'
import MiniProgramAdapter from 'axios-miniprogram-adapter';
import { BASE_URL } from '@/config/index.js';

const noErrerApi = [
	'/v7_2_6/member/findByInviteCode',
	'/common/shop/publicKey',
	'/v7_2_6/member/bindInviteCode',
	'/weixin/miniApp/getXcxQRCode'
]

axios.defaults.adapter = MiniProgramAdapter;
const Service = axios.create({
	baseURL: BASE_URL,
	timeout: 7000
})

Service.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
Service.defaults.headers.post['callSource'] = 'https://retail-h5-dev.diwangxu.com';	
// 请求拦截
Service.interceptors.request.use(config => {
	config.headers['Appkey'] = 'APP';
	let token = uni.getStorageSync('token');
	if (token) {
		config.headers['loginToken'] = token;
	};
	const sessionGenerateId = uni.getStorageSync('sessionGenerateId');
	config.headers['sessionGenerateId'] = sessionGenerateId;
	return config
})

Service.interceptors.response.use(response => {
	if (response.data.code === 102) {
		uni.reLaunch({
			url:'/pages/login/login'
		})
	} else if (response.data.code != 100) {
		if (!noErrerApi.includes(response.request.url)) {
			uni.$uv.toast(response.data.msg);
		}
	}
	return response.data
}, error => {
	console.log('TCL: error', error)
	const msg = error.Message !== undefined ? error.Message : '网络错误';
	uni.$uv.toast(msg);
	return Promise.reject(error)
})

export default Service


export function post(url, data = {}) {
	console.log(url,data)
  return new Promise((resolve, reject) => {
    Service
      .post(url, data)
      .then((response) => {
        resolve(response);
      })
      .catch((err) => {
        reject(err);
      });
  });
}